package com.yaozheng.vocationaltraining.fragment;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.photoselector.model.PhotoModel;
import com.photoselector.ui.PhotoSelectorActivity;
import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.activity.HomeActivity;
import com.yaozheng.vocationaltraining.adapter.MyUserInfoDataAdapter;
import com.yaozheng.vocationaltraining.dialog.time.SelectTimeDateDialog;
import com.yaozheng.vocationaltraining.dialog.userinfo.ListViewSelectDialog;
import com.yaozheng.vocationaltraining.dialog.userinfo.SaxDialog;
import com.yaozheng.vocationaltraining.dialog.userinfo.WhetherDialog;
import com.yaozheng.vocationaltraining.iview.IMyUserInfoView;
import com.yaozheng.vocationaltraining.iview.userinfo.IBasicDataView;
import com.yaozheng.vocationaltraining.iview.userinfo.ILogoutView;
import com.yaozheng.vocationaltraining.iview.userinfo.IUpdateUserInfoView;
import com.yaozheng.vocationaltraining.service.MyUserInfoService;
import com.yaozheng.vocationaltraining.service.impl.MyUserInfoServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.userinfo.BasicDataServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.userinfo.LogoutServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.userinfo.UpdateUserInfoServiceImpl;
import com.yaozheng.vocationaltraining.service.userinfo.BasicDataService;
import com.yaozheng.vocationaltraining.service.userinfo.LogoutService;
import com.yaozheng.vocationaltraining.service.userinfo.UpdateUserInfoService;
import com.yaozheng.vocationaltraining.utils.BitmapLoader;
import com.yaozheng.vocationaltraining.utils.Constants;
import com.yaozheng.vocationaltraining.utils.DateUtils;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.FileUtils;
import com.yaozheng.vocationaltraining.utils.LogUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;
import com.yaozheng.vocationaltraining.view.HeadMyUserInfoView;
import com.yaozheng.vocationaltraining.view.HeadMyUserInfoView_;
import com.yaozheng.vocationaltraining.view.time.SelectTimeDatePickerDialogView;
import com.yaozheng.vocationaltraining.view.userinfo.ListViewSelectDialogView;

/**
 * 我的个人中心
 *
 * @author Administrator
 */
@EFragment(R.layout.fragment_my_user_info)
public class MyUserInfoFragment extends BaseFragment implements
        IMyUserInfoView, SwipeRefreshLayout.OnRefreshListener, ListViewSelectDialogView.ListViewSelectDialogViewItemClick, ILogoutView, IUpdateUserInfoView, IBasicDataView {
    /**
     * 大区数据
     */
    public static final String[]
            REGION_BASE_DATE_STR = new String[]{"华北", "华东", "华南", "华中", "东北", "西北", "西南"};
    /**
     * 经销商
     */
    public static final String[]
            DEALER_BASE_DATE_STR = new String[]{"建国宝沃"};

    /**
     * 职位
     */
    public static final String[]
            POSITION_BASE_DATE_STR = new String[]{"品牌经理", "品牌顾问", "商品经理", "商品顾问", "销售经理", "销售顾问", "服务经理", "服务顾问", "技术经理", "技术顾问"};

    /**
     * 民族
     */
    public static final String[]
            NATION_BASE_DATE_STR = new String[]{"汉族",
            "壮族",
            "满族",
            "回族",
            "苗族",
            "维吾尔族",
            "土家族",
            "彝族",
            "蒙古族",
            "藏族",
            "布依族",
            "侗族",
            "瑶族",
            "朝鲜族",
            "白族",
            "哈尼族",
            "哈萨克族",
            "黎族",
            "傣族",
            "畲族",
            "傈僳族",
            "仡佬族",
            "东乡族",
            "高山族",
            "拉祜族",
            "水族",
            "佤族",
            "纳西族",
            "羌族",
            "土族",
            "仫佬族",
            "锡伯族",
            "柯尔克孜族",
            "达斡尔族",
            "景颇族",
            "毛南族",
            "撒拉族",
            "塔吉克族",
            "阿昌族",
            "普米族",
            "鄂温克族",
            "怒族",
            "京族",
            "基诺族",
            "德昂族",
            "保安族",
            "俄罗斯族",
            "裕固族",
            "乌兹别克族",
            "门巴族",
            "鄂伦春族",
            "独龙族",
            "塔塔尔族",
            "赫哲族",
            "珞巴族",
            "布朗族"};

    /**
     * 学历
     */
    public static final String[]
            EDUCATION_BASE_DATE_STR = new String[]{"博士", "硕士", "研究生", "本科", "大专", "职高", "高中", "初中", "小学"};

    /**
     * 专业
     */
    public static final String[]
            PROFESSION_BASE_DATE_STR = new String[]{"汽车专业", "非汽车专业"};

    /**
     * 驾照
     */
    public static final String[]
            DRIVE_PHOTO_BASE_DATE_STR = new String[]{"A1", "A2", "A3", "B1", "B2", "C1", "C2", "C3", "C4", "D", "E", "F", "M", "N", "P"};
    /**
     * 血型
     */
    public static final String[]
            BLOOD_TYPE_BASE_DATE_STR = new String[]{"A", "B", "O", "AB"};

    /**
     * 相册
     */
    public static final String[] PHOTO_GALLERY_STR = new String[]{"拍头像", "从相册选取"};

    @ViewById
    TextView headTitleText, headRightText;
    @ViewById
    ListView listView;

    /**
     * 下拉刷新
     */
    @ViewById
    SwipeRefreshLayout swipeRefreshLayout;
    /**
     * 当前用户资料
     */
    JSONObject currUserInfJsonObject;
    /**
     * 当前数组
     */
    JSONArray currUserInfoJsonArray;

    SimpleDateFormat simpleDateFormat;

    MyUserInfoDataAdapter myUserInfoDataAdapter = null;

    @Bean(MyUserInfoServiceImpl.class)
    MyUserInfoService myUserInfoService;
    @Bean(UpdateUserInfoServiceImpl.class)
    UpdateUserInfoService updateUserInfoService;

    @Bean(LogoutServiceImpl.class)
    LogoutService logoutService;
    @Bean(BasicDataServiceImpl.class)
    BasicDataService basicDataService;
    // DisplayImageOptions avatarDisplayImageOptions;

    HeadMyUserInfoView headMyUserInfoView;

    @ViewById
    ImageView headRightImage;

    /**
     * 是否修改数据
     */
    boolean isUpdateData;

    BitmapLoader bitmapLoader;
    /**
     * 选择性别对话
     */
    SaxDialog saxDialog;
    /**
     * 选择时间
     */
    SelectTimeDateDialog selectTimeDateDialog;

    /**
     * 列表选择对话框
     */
    ListViewSelectDialog listSelectDialog;
    /**
     * 是否兼职选择
     */
    WhetherDialog whetherDialog;
    /**
     * json
     */
    JSONArray regionJSONArray, dealerJSONArray, positionJSONArray, nationJSONArray, educationJSONArray, professionJSONArray, drive_photoJSONArray, blood_typeJSONArray,
            photoGalleryJsonArray;

    JSONArray currSelectDataList;

    JSONObject userInfoItemData;

    int currPosition;
    /**
     * 选中列表执行方法
     */
    String selectListRunMethod;

    public HomeActivity getHomeActivity() {
        return (HomeActivity) getBaseActivity();
    }

    @AfterViews
    public void initView() {
        headTitleText.setText("我的信息");
        headRightText.setTextColor(getResources().getColor(R.color.leran_list_type_item_selected_font_color));
        headRightText.setText("提交");
        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        bitmapLoader = new BitmapLoader(Glide.with(this), R.drawable.user_img);
        initBaseData();
        headMyUserInfoView = HeadMyUserInfoView_.build(getContext());
        headMyUserInfoView.init(this);
        updateUserInfoService.init(this);
        basicDataService.init(this);
        listView.addHeaderView(headMyUserInfoView);
        // avatarDisplayImageOptions = ImageUtils
        // .getUserAvatarDisplayImageOptions(getBaseActivity());
        myUserInfoService.init(this);
        logoutService.init(this);
        headRightImage.setImageResource(R.drawable.save_button_image_ioc);
        headRightImage.setVisibility(View.GONE);
        headRightText.setVisibility(View.GONE);
//        swipeRefreshLayout.postDelayed(new Runnable() {
//
//            @Override
//            public void run() {
//                swipeRefreshLayout.setRefreshing(true);
//                onRefresh();
//
//            }
//        }, 500);
        onRefresh();
        isUpdateData = false;
        swipeRefreshLayout.setOnRefreshListener(this);

        myUserInfoDataAdapter = new MyUserInfoDataAdapter(
                currUserInfoJsonArray, getBaseActivity());
        listView.setAdapter(myUserInfoDataAdapter);

    }


    public void initBaseData() {
        currUserInfoJsonArray = new JSONArray();
        //JsonUtils.getJsonArray(userJson);
        JSONObject idJsonObject = new JSONObject();
        idJsonObject.put("name", "id");
        idJsonObject.put("nameKey", "id");
        idJsonObject.put("isUpdate", 1);
        idJsonObject.put("icon_left", R.drawable.icon_id);
        currUserInfoJsonArray.add(idJsonObject);

        JSONObject userNameJsonObject = new JSONObject();
        userNameJsonObject.put("name", "用户名");
        userNameJsonObject.put("nameKey", "username");
        userNameJsonObject.put("isUpdate", 1);
        userNameJsonObject.put("icon_left", R.drawable.icon_username);
        currUserInfoJsonArray.add(userNameJsonObject);

        JSONObject nameJsonObject = new JSONObject();
        nameJsonObject.put("name", "姓名");
        nameJsonObject.put("nameKey", "name");
        nameJsonObject.put("isUpdate", 2);
        nameJsonObject.put("icon_left", R.drawable.icon_name);
        currUserInfoJsonArray.add(nameJsonObject);

        JSONObject passwordJsonObject = new JSONObject();
        passwordJsonObject.put("name", "密码");
        passwordJsonObject.put("nameKey", "password");
        passwordJsonObject.put("isUpdate", 2);
        passwordJsonObject.put("icon_left", R.drawable.icon_password);
        currUserInfoJsonArray.add(passwordJsonObject);
        JSONObject genderJsonObject = new JSONObject();
        genderJsonObject.put("name", "性别");
        genderJsonObject.put("nameKey", "gender");
        genderJsonObject.put("isUpdate", 2);
        genderJsonObject.put("icon_left", R.drawable.icon_gender);
        currUserInfoJsonArray.add(genderJsonObject);

        JSONObject jobNumberJsonObject = new JSONObject();
        jobNumberJsonObject.put("name", "工号");
        jobNumberJsonObject.put("nameKey", "jobNumber");
        jobNumberJsonObject.put("isUpdate", 2);
        jobNumberJsonObject.put("icon_left", R.drawable.icon_job_number);
        currUserInfoJsonArray.add(jobNumberJsonObject);

        JSONObject experienceTitleJsonObject = new JSONObject();
        experienceTitleJsonObject.put("name", "头衔");
        experienceTitleJsonObject.put("nameKey", "experienceTitle");
        experienceTitleJsonObject.put("isUpdate", 1);
        experienceTitleJsonObject.put("icon_left", R.drawable.icon_experience_my_user);
        currUserInfoJsonArray.add(experienceTitleJsonObject);

        JSONObject masterJsonObject = new JSONObject();
        masterJsonObject.put("name", "大师勋章");
        masterJsonObject.put("nameKey", "medals");
        masterJsonObject.put("isUpdate", 1);
        masterJsonObject.put("icon_left", R.drawable.icon_master);
        currUserInfoJsonArray.add(masterJsonObject);

        JSONObject birthDayJsonObject = new JSONObject();
        birthDayJsonObject.put("name", "出生日期");
        birthDayJsonObject.put("nameKey", "birthDay");
        birthDayJsonObject.put("isUpdate", 2);
        birthDayJsonObject.put("icon_left", R.drawable.icon_birth_day);
        currUserInfoJsonArray.add(birthDayJsonObject);


        JSONObject ageJsonObject = new JSONObject();
        ageJsonObject.put("name", "年龄");
        ageJsonObject.put("nameKey", "age");
        ageJsonObject.put("isUpdate", 1);
        ageJsonObject.put("icon_left", R.drawable.icon_age);
        currUserInfoJsonArray.add(ageJsonObject);


        JSONObject regionObject = new JSONObject();
        regionObject.put("name", "所属大区");
        regionObject.put("nameKey", "region");
        regionObject.put("isUpdate", 1);
        regionObject.put("icon_left", R.drawable.icon_region);
        currUserInfoJsonArray.add(regionObject);

        JSONObject dealerObject = new JSONObject();
        dealerObject.put("name", "所属经销商");
        dealerObject.put("nameKey", "dealer");
        dealerObject.put("isUpdate", 1);
        dealerObject.put("icon_left", R.drawable.icon_dealer);
        currUserInfoJsonArray.add(dealerObject);

        JSONObject positionObject = new JSONObject();
        positionObject.put("name", "职位");
        positionObject.put("nameKey", "position");
        positionObject.put("isUpdate", 2);
        positionObject.put("icon_left", R.drawable.icon_position);
        currUserInfoJsonArray.add(positionObject);

        JSONObject mobileObject = new JSONObject();
        mobileObject.put("name", "手机号");
        mobileObject.put("nameKey", "mobile");
        mobileObject.put("isUpdate", 2);
        mobileObject.put("inputType", InputType.TYPE_CLASS_PHONE);
//        mobileObject.put("regularExpressions", "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
//        mobileObject.put("errorMessage", "手机号格式不正确");
        mobileObject.put("icon_left", R.drawable.icon_mobile);
        currUserInfoJsonArray.add(mobileObject);


        JSONObject wechatObject = new JSONObject();
        wechatObject.put("name", "微信号");
        wechatObject.put("nameKey", "wechat");
        wechatObject.put("isUpdate", 2);
        wechatObject.put("icon_left", R.drawable.icon_wechat);
        currUserInfoJsonArray.add(wechatObject);

        JSONObject qqObject = new JSONObject();
        qqObject.put("name", "QQ");
        qqObject.put("nameKey", "qq");
        qqObject.put("inputType", InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
        qqObject.put("isUpdate", 2);
        qqObject.put("icon_left", R.drawable.icon_qq);
        currUserInfoJsonArray.add(qqObject);

        JSONObject emailObject = new JSONObject();
        emailObject.put("name", "邮箱");
        emailObject.put("nameKey", "email");
        emailObject.put("isUpdate", 2);
        emailObject.put("icon_left", R.drawable.icon_email);
        emailObject.put("regularExpressions", "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
        emailObject.put("errorMessage", "邮箱格式不正确");
        currUserInfoJsonArray.add(emailObject);

        JSONObject idCardObject = new JSONObject();
        idCardObject.put("name", "身份证号");
        idCardObject.put("nameKey", "idCard");
        idCardObject.put("isUpdate", 2);
        idCardObject.put("icon_left", R.drawable.icon_id_card);
        currUserInfoJsonArray.add(idCardObject);

        JSONObject nationObject = new JSONObject();
        nationObject.put("name", "民族");
        nationObject.put("nameKey", "nation");
        nationObject.put("isUpdate", 2);
        nationObject.put("icon_left", R.drawable.icon_nation);
        currUserInfoJsonArray.add(nationObject);

        JSONObject educationObject = new JSONObject();
        educationObject.put("name", "最高学历");
        educationObject.put("nameKey", "education");
        educationObject.put("isUpdate", 2);
        educationObject.put("icon_left", R.drawable.icon_education);
        currUserInfoJsonArray.add(educationObject);

        JSONObject specialtyObject = new JSONObject();
        specialtyObject.put("name", "专业");
        specialtyObject.put("nameKey", "specialty");
        specialtyObject.put("isUpdate", 2);
        specialtyObject.put("icon_left", R.drawable.icon_specialty);
        currUserInfoJsonArray.add(specialtyObject);

        JSONObject industryTimeObject = new JSONObject();
        industryTimeObject.put("name", "行业经验");
        industryTimeObject.put("nameKey", "industryTime");
        industryTimeObject.put("isUpdate", 2);
        industryTimeObject.put("icon_left", R.drawable.icon_industry_time);
        currUserInfoJsonArray.add(industryTimeObject);

        JSONObject industryBrandObject = new JSONObject();
        industryBrandObject.put("name", "从业品牌");
        industryBrandObject.put("nameKey", "industryBrand");
        industryBrandObject.put("isUpdate", 2);
        industryBrandObject.put("icon_left", R.drawable.icon_industry_brand);
        currUserInfoJsonArray.add(industryBrandObject);


        JSONObject parttimeObject = new JSONObject();
        parttimeObject.put("name", "兼职");
        parttimeObject.put("nameKey", "parttime");
        parttimeObject.put("isUpdate", 2);
        parttimeObject.put("icon_left", R.drawable.icon_parttime);
        currUserInfoJsonArray.add(parttimeObject);


        JSONObject driveLicenseTypeObject = new JSONObject();
        driveLicenseTypeObject.put("name", "驾照类型");
        driveLicenseTypeObject.put("nameKey", "driveLicenseType");
        driveLicenseTypeObject.put("isUpdate", 2);
        driveLicenseTypeObject.put("icon_left", R.drawable.icon_drive_license_type);
        currUserInfoJsonArray.add(driveLicenseTypeObject);

        JSONObject driveLicenseApplicationDateObject = new JSONObject();
        driveLicenseApplicationDateObject.put("name", "驾龄");
        driveLicenseApplicationDateObject.put("nameKey", "driveLicenseApplicationDate");
        driveLicenseApplicationDateObject.put("isUpdate", 2);
        driveLicenseApplicationDateObject.put("icon_left", R.drawable.icon_drive_license_application_date);
        currUserInfoJsonArray.add(driveLicenseApplicationDateObject);

        JSONObject birthDayConstellationObject = new JSONObject();
        birthDayConstellationObject.put("name", "星座");
        birthDayConstellationObject.put("nameKey", "birthDayConstellation");
        birthDayConstellationObject.put("isUpdate", 1);
        birthDayConstellationObject.put("icon_left", R.drawable.icon_constellation);
        currUserInfoJsonArray.add(birthDayConstellationObject);

        JSONObject bloodTypeObject = new JSONObject();
        bloodTypeObject.put("name", "血型");
        bloodTypeObject.put("nameKey", "bloodType");
        bloodTypeObject.put("isUpdate", 2);
        bloodTypeObject.put("icon_left", R.drawable.icon_blood_type);
        currUserInfoJsonArray.add(bloodTypeObject);
        regionJSONArray = ListViewSelectDialogView.stringArrayToJsonArray(REGION_BASE_DATE_STR);
        dealerJSONArray = ListViewSelectDialogView.stringArrayToJsonArray(DEALER_BASE_DATE_STR);
        positionJSONArray = ListViewSelectDialogView.stringArrayToJsonArray(POSITION_BASE_DATE_STR);
        nationJSONArray = ListViewSelectDialogView.stringArrayToJsonArray(NATION_BASE_DATE_STR);
        educationJSONArray = ListViewSelectDialogView.stringArrayToJsonArray(EDUCATION_BASE_DATE_STR);
        professionJSONArray = ListViewSelectDialogView.stringArrayToJsonArray(PROFESSION_BASE_DATE_STR);
        drive_photoJSONArray = ListViewSelectDialogView.stringArrayToJsonArray(DRIVE_PHOTO_BASE_DATE_STR);
        blood_typeJSONArray = ListViewSelectDialogView.stringArrayToJsonArray(BLOOD_TYPE_BASE_DATE_STR);
        photoGalleryJsonArray = ListViewSelectDialogView.stringArrayToJsonArray(PHOTO_GALLERY_STR);

    }


    /**
     * 设置点击
     */
    public void setUpClick(View view) {
        getHomeActivity().openSetUpFragment();
    }

    @UiThread
    @Override
    public void responseSuccess(JSONObject jsonObject) {
        cancelLoadDataProgressDialog();
        currUserInfJsonObject = TypeUtils.getJsonObject(jsonObject, "data",
                "user");
        if (currUserInfJsonObject != null) {
            if (currUserInfoJsonArray != null) {
                for (int i = 0; i < TypeUtils
                        .getJsonArraySize(currUserInfoJsonArray); i++) {
                    JSONObject itemJsonObject = TypeUtils.getJsonObject(
                            currUserInfoJsonArray, i);

                    String nameKey = TypeUtils.getJsonString(itemJsonObject, "nameKey");
                    if ("password".equals(nameKey)) {
                        itemJsonObject.put("showValue", "");
                        itemJsonObject.put("value", "");
                    } else if ("medals".equals(nameKey)) {
                        JSONArray medals = TypeUtils.getJsonArray(currUserInfJsonObject, "medals");
                        itemJsonObject.put("showValue", "大师勋章");
                        itemJsonObject.put("value", medals);
                    } else {
                        String showValue = getItemJsonObjectValue(itemJsonObject);
                        if (showValue == null || "null".equals(showValue)) {
                            itemJsonObject.put("showValue", "");
                        } else {
                            itemJsonObject.put("showValue", showValue);
                        }
                        if ("industryBrand".equals(nameKey)) {
                            itemJsonObject.put("value", showValue);
                        } else {
                            String value = TypeUtils.getJsonString(currUserInfJsonObject, nameKey, "");
                            if (value == null || "null".equals(value)) {
                                itemJsonObject.put("value", "");
                            } else {
                                itemJsonObject.put("value", value);
                            }
                        }
                    }
                }
                headMyUserInfoView
                        .loadData(currUserInfJsonObject, bitmapLoader);
                isUpdateData = false;
                if (myUserInfoDataAdapter == null) {
                    myUserInfoDataAdapter = new MyUserInfoDataAdapter(
                            currUserInfoJsonArray, getBaseActivity());
                    listView.setAdapter(myUserInfoDataAdapter);
                } else {
                    myUserInfoDataAdapter.notifyDataSetChanged();
                }

            }
        }
    }

    @UiThread
    @Override
    public void basicDataSuccess(JSONObject jsonObject) {
//        regionJSONArray, dealerJSONArray, positionJSONArray, nationJSONArray, educationJSONArray,
//                professionJSONArray, drive_photoJSONArray, blood_typeJSONArray, photoGalleryJsonArray;
//        头衔	ExperienceTitle
//        大区	regions    regionJSONArray
//        经销商 Store      dealerJSONArray
//        职位	positions    positionJSONArray
//        民族	nations     nationJSONArray
//        专业	specialties professionJSONArray
//        学历	educations educationJSONArray
//        品牌	Brand  填写的方式
//        血型	bloodType blood_typeJSONArray
//        驾照	driveLicenses drive_photoJSONArray
        JSONObject dataJsonObject = TypeUtils.getJsonObject(jsonObject, "data");

//        dealerJSONArray=TypeUtils.getJsonArray(dataJsonObject,"Store");
        positionJSONArray = TypeUtils.getJsonArray(dataJsonObject, "positions");
        nationJSONArray = TypeUtils.getJsonArray(dataJsonObject, "nations");
        professionJSONArray = TypeUtils.getJsonArray(dataJsonObject, "specialties");
        educationJSONArray = TypeUtils.getJsonArray(dataJsonObject, "educations");
        blood_typeJSONArray = TypeUtils.getJsonArray(dataJsonObject, "bloodType");
        drive_photoJSONArray = TypeUtils.getJsonArray(dataJsonObject, "driveLicenses");
        regionJSONArray = TypeUtils.getJsonArray(dataJsonObject, "regions");
    }

    @UiThread
    @Override
    public void basicDataError(String error) {
        alertMessage(error);
    }

    /**
     * 得到一项值
     *
     * @param itemJsonObject
     * @return
     */
    private String getItemJsonObjectValue(JSONObject itemJsonObject) {
        String nameKey = TypeUtils.getJsonString(itemJsonObject, "nameKey");
        if ("gender".equals(nameKey)) {
            return gender(currUserInfJsonObject);
        } else if ("age".equals(nameKey)) {
            return calculationDay(currUserInfJsonObject, "birthDay");
        } else if ("birthDayConstellation".equals(nameKey)) {
            return birthDayConstellation(currUserInfJsonObject);
        } else if ("parttime".equals(nameKey)) {
            return parttime(currUserInfJsonObject);
        } else if ("industryBrand".equals(nameKey)) {
            return industryBrand(currUserInfJsonObject);
        } else if ("industryTime".equals(nameKey)) {
            return calculationDay(currUserInfJsonObject, nameKey);
        } else if ("driveLicenseApplicationDate".equals(nameKey)) {
            return calculationDay(currUserInfJsonObject, nameKey);
        }
        return TypeUtils.getJsonString(currUserInfJsonObject, nameKey);
    }

    /**
     * 性别
     *
     * @param itemJsonObject
     * @return
     */
    private String gender(JSONObject itemJsonObject) {
        // 0-未知；1-男；2-女
        return TypeUtils.getJsonInteger(itemJsonObject, "gender", 1) == 1 ? "男"
                : "女";
    }

    /**
     * 计算年年龄
     *
     * @param itemJsonObject
     * @return
     */
    private String calculationDay(JSONObject itemJsonObject, String nameKey) {
        String birthDay = TypeUtils.getJsonString(itemJsonObject, nameKey);
        try {
            return String.valueOf(DateUtils.getAge(simpleDateFormat
                    .parse(birthDay)));
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
        }
        return "";
    }

    /**
     * 星座
     *
     * @param itemJsonObject
     * @return
     */
    private String birthDayConstellation(JSONObject itemJsonObject) {

        String birthDay = TypeUtils.getJsonString(itemJsonObject, "birthDay");
        try {
            return DateUtils.getConstellation(simpleDateFormat.parse(birthDay));
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
        }
        return "";
    }

    /**
     * 是否兼职
     *
     * @param itemJsonObject
     * @return
     */
    public String parttime(JSONObject itemJsonObject) {
        return TypeUtils.getJsonBoolean(itemJsonObject, "parttime") ? "是" : "否";
    }

    /**
     * 从业品牌
     *
     * @param itemJsonObject
     * @return
     */
    public String industryBrand(JSONObject itemJsonObject) {
        StringBuffer industryBrandStringBuffer = new StringBuffer();
        JSONArray industryBrandJsonArray = TypeUtils.getJsonArray(
                itemJsonObject, "industryBrand");
        for (int i = 0; i < TypeUtils.getJsonArraySize(industryBrandJsonArray); i++) {
            industryBrandStringBuffer.append(TypeUtils.getJsonString(
                    industryBrandJsonArray, i));
            if (i < TypeUtils.getJsonArraySize(industryBrandJsonArray) - 1) {
                industryBrandStringBuffer.append(",");
            }
        }
        return industryBrandStringBuffer.toString();
    }

    @UiThread
    @Override
    public void responseError(String error) {
        cancelLoadDataProgressDialog();
        alertMessage(error);
    }

    @Override
    public void cancelLoadDataProgressDialog() {
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onRefresh() {
        loadData();
    }

    /**
     * 加载数据
     */
    public void loadData() {
        basicDataService.getBasicData();
        myUserInfoService.getUserInfo();
    }

    /**
     * 显示选中对话框
     *
     * @param title
     * @param selectRunMethod
     * @param dataList
     */
    public void showListSelectAlertDialog(String title, String selectRunMethod, JSONArray dataList) {
        if (listSelectDialog == null) {
            listSelectDialog = new ListViewSelectDialog(getContext());

        }
        this.selectListRunMethod = selectRunMethod;
        listSelectDialog.show();
        this.currSelectDataList = dataList;
        ListViewSelectDialogView listViewSelectDialogView = listSelectDialog.getListViewSelectDialogView();
        listViewSelectDialogView.setTitle(title);
        listViewSelectDialogView.setListViewSelectDialogViewItemClick(this);
        listViewSelectDialogView.setDataList(dataList);
    }

    /**
     * 显示是否兼职对话框
     */
    public void showWhetherDialog() {
        if (whetherDialog == null) {
            whetherDialog = new WhetherDialog(this);
        }
        whetherDialog.show();
        whetherDialog.setTitleAndroidContent("请选择", "是否兼职？");
        whetherDialog.setRunMethod("whetherDialogYesClick");
        whetherDialog.setNoClickRunMethod("whetherDialogNoClick");
    }

    /**
     * 是兼职点击
     */
    public void whetherDialogYesClick() {
        userInfoItemData.put("showValue", "是");
        userInfoItemData.put("value", "1");
        dataUpdate();
    }

    /**
     * 不是(否)兼职点击
     */
    public void whetherDialogNoClick() {
        userInfoItemData.put("showValue", "否");
        userInfoItemData.put("value", "0");
        dataUpdate();
    }

    /**
     * 女点击
     */
    public void saxDialogAllClick() {
        userInfoItemData.put("showValue", "女");
        userInfoItemData.put("value", "2");
        dataUpdate();
    }

    /**
     * 男点击
     */
    public void saxDialogManClick() {
        userInfoItemData.put("showValue", "男");
        userInfoItemData.put("value", "1");
        dataUpdate();
    }

    /**
     * 选择年龄点击
     */
    public void selectTimeDatePickerDialogBirthDay() {
        if (selectTimeDateDialog != null) {
            SelectTimeDatePickerDialogView selectTimeDatePickerDialogView = selectTimeDateDialog.getSelectTimeDatePickerDialogView();
            long time = selectTimeDatePickerDialogView.getCurrTime();
            long currTime = System.currentTimeMillis();
            if (currTime < time) {
                alertMessage("日期不能大于当前日期");
                return;
            }
            selectTimeDateDialog.cancel();
            String value = selectTimeDatePickerDialogView.getCurrDate();
            JSONObject ageJsonObject = TypeUtils.getJsonObject(currUserInfoJsonArray, currPosition + 1);
            JSONObject birthDayConstellationJsonObject = TypeUtils.getJsonObject(currUserInfoJsonArray, TypeUtils.getJsonArraySize(currUserInfoJsonArray) - 2);
            userInfoItemData.put("value", value);
            userInfoItemData.put("showValue", value);
            try {
                //年龄
                String showValue = String.valueOf(DateUtils.getAge(simpleDateFormat.parse(value)));
                ageJsonObject.put("value", showValue);
                ageJsonObject.put("showValue", showValue);
            } catch (Exception e) {
                ErrorUtils.outErrorLog(e);
//                ageJsonObject.put("value", -1);
//                ageJsonObject.put("showValue", -1);
            }

            try {
                //星座
                String showValue = DateUtils.getConstellation(simpleDateFormat.parse(value));
                birthDayConstellationJsonObject.put("value", showValue);

                birthDayConstellationJsonObject.put("showValue", showValue);
            } catch (Exception e) {
                ErrorUtils.outErrorLog(e);
//                birthDayConstellationJsonObject.put("value", "");
//                birthDayConstellationJsonObject.put("showValue", "");
            }
            dataUpdate();

        }
    }

    /**
     * 选择驾照年龄点击
     */
    public void selectTimeDatePickerDialogDrivingExperience() {
        if (selectTimeDateDialog != null) {
            SelectTimeDatePickerDialogView selectTimeDatePickerDialogView = selectTimeDateDialog.getSelectTimeDatePickerDialogView();
            long time = selectTimeDatePickerDialogView.getCurrTime();
            long currTime = System.currentTimeMillis();
            if (currTime < time) {
                alertMessage("日期不能大于当前日期");
                return;
            }
            selectTimeDateDialog.cancel();
            String value = selectTimeDatePickerDialogView.getCurrDate();

            try {
                //年龄
                String showValue = String.valueOf(DateUtils.getAge(simpleDateFormat.parse(value)));
                userInfoItemData.put("value", value);
                userInfoItemData.put("showValue", showValue);
            } catch (Exception e) {
                ErrorUtils.outErrorLog(e);
//                userInfoItemData.put("value", -1);
//                userInfoItemData.put("showValue", -1);
            }
            dataUpdate();
        }
    }


    /**
     * 选择驾照年龄点击
     */
    public void selectTimeDatePickerDialogIndustryTime() {
        if (selectTimeDateDialog != null) {
            SelectTimeDatePickerDialogView selectTimeDatePickerDialogView = selectTimeDateDialog.getSelectTimeDatePickerDialogView();
            long time = selectTimeDatePickerDialogView.getCurrTime();
            long currTime = System.currentTimeMillis();
            if (currTime < time) {
                alertMessage("日期不能大于当前日期");
                return;
            }
            selectTimeDateDialog.cancel();
            String value = selectTimeDatePickerDialogView.getCurrDate();

            try {
                String showValue = String.valueOf(DateUtils.getAge(simpleDateFormat.parse(value)));
                userInfoItemData.put("value", value);
                userInfoItemData.put("showValue", showValue);
            } catch (Exception e) {
                ErrorUtils.outErrorLog(e);
            }
            dataUpdate();
        }
    }

    @Override
    public void itemClick(int position) {
        if ("photoGallerySelect".equals(selectListRunMethod)) {
            photoGallerySelect(position);

        } else {
            JSONObject jsonObject = TypeUtils.getJsonObject(currSelectDataList, position);
            LogUtils.println("jsonObject" + jsonObject);
            if (listSelectDialog != null && listSelectDialog.isShowing()) {
                listSelectDialog.cancel();
            }
            if (jsonObject != null && userInfoItemData != null) {
                String value = TypeUtils.getJsonString(jsonObject, "name");
                userInfoItemData.put("showValue", value);
                userInfoItemData.put("value", value);
                dataUpdate();
                LogUtils.println("数据修改" + value);
            }
        }
    }

    /**
     * 点击
     *
     * @param position
     */
    @ItemClick(R.id.listView)
    public void itemRootViewClick(int position) {
        currPosition = position - 1;
        userInfoItemData = TypeUtils.getJsonObject(currUserInfoJsonArray,
                currPosition);

        String nameKey = TypeUtils.getJsonString(userInfoItemData, "nameKey");
        if (userInfoItemData == null) return;
//        LogUtils.println(userInfoItemData.toString());
        if ("gender".equals(nameKey)) {
            showSelectSaxDialog();
            return;
        } else if ("birthDay".equals(nameKey)) {

            showSelectTimeDateDialog("选择出生日期", "selectTimeDatePickerDialogBirthDay", TypeUtils.getJsonString(userInfoItemData, "value"));
            return;
        } else if ("driveLicenseApplicationDate".equals(nameKey)) {
            showSelectTimeDateDialog("选择驾照申领开始时间", "selectTimeDatePickerDialogDrivingExperience", TypeUtils.getJsonString(userInfoItemData, "value"));
            return;
        } else if ("industryTime".equals(nameKey)) {
            showSelectTimeDateDialog("选择从业开始时间", "selectTimeDatePickerDialogIndustryTime", TypeUtils.getJsonString(userInfoItemData, "value"));
            return;
        } else if ("parttime".equals(nameKey)) {
            showWhetherDialog();
            return;
        } else if ("region".equals(nameKey)) {

//            showListSelectAlertDialog("选择大区", "regionSelect", regionJSONArray);
            return;
        } else if ("dealer".equals(nameKey)) {

//            showListSelectAlertDialog("选择经销商", "dealerSelect", dealerJSONArray);
            return;
        } else if ("position".equals(nameKey)) {

            showListSelectAlertDialog("选择职位", "positionSelect", positionJSONArray);
            return;
        } else if ("nation".equals(nameKey)) {

            showListSelectAlertDialog("选择名族", "nationSelect", nationJSONArray);
            return;
        } else if ("education".equals(nameKey)) {

            showListSelectAlertDialog("最高学历", "educationSelect", educationJSONArray);
            return;
        } else if ("specialty".equals(nameKey)) {

            showListSelectAlertDialog("选择专业", "specialtySelect", professionJSONArray);
            return;
        } else if ("driveLicenseType".equals(nameKey)) {

            showListSelectAlertDialog("选择驾照", "drivePhotoSelect", drive_photoJSONArray);
            return;
        } else if ("bloodType".equals(nameKey)) {

            showListSelectAlertDialog("选择血型", "bloodTypeSelect", blood_typeJSONArray);
            return;
        } else if ("password".equals(nameKey)) {
            getHomeActivity().openUpdatePasswordFragment();
        } else if (2 == TypeUtils.getJsonInteger(userInfoItemData, "isUpdate", 1)) {
//            Intent intent = new Intent();
//            intent.putExtra("title", "修改" + userInfoItemData.optString("name"));
//            intent.putExtra("value", userInfoItemData.optString("value"));
//            intent.putExtra("showValue", userInfoItemData.optString("showValue"));
//            intent.putExtra("position", position - 1);
//            intent.setClassName(getContext(),
//                    Constants.UPDATE_DATA_ACTIVITY_CLASS_NAME);
//            startActivityForResult(intent,
//                    Constants.UPDATE_USER_INFO_REQUEST_CODE);
            getHomeActivity().openUpdateUserInfoFragment("修改" + TypeUtils.getJsonString(userInfoItemData, "name"), TypeUtils.getJsonString(userInfoItemData, "value"), currPosition, currUserInfoJsonArray);
        } else {

        }
    }
//
//    /**
//     * 打开相册
//     */
//    public void cutOutPhoto() {
//        Intent intent = new Intent(getBaseActivity(),
//                PhotoSelectorActivity.class);
//        intent.putExtra(PhotoSelectorActivity.KEY_MAX, 1);
//        startActivityForResult(intent, Constants.SELECT_IMAGE_REQUEST_CODE);
//    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == Constants.UPDATE_USER_INFO_REQUEST_CODE && resultCode == Constants.UPDATE_USER_INFO_RESULT_CODE) {
            // 处理结果
            int position = data.getIntExtra("position", -1);
            // currUserInfoJsonArray
            JSONObject itemData = TypeUtils.getJsonObject(
                    currUserInfoJsonArray, position);
            if (2 == TypeUtils.getJsonInteger(itemData, "isUpdate", 1)) {
                String newValue = data.getStringExtra("newValue");
                itemData.put("value", newValue);
                itemData.put("showValue", newValue);
                if (myUserInfoDataAdapter != null) {
                    dataUpdate();

                }
            }
        } else if (requestCode == Constants.STYEM_SHEAR_PHOTO_GALLERY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {

            //剪切图片
            cutOutImage();
        } else if (resultCode == Activity.RESULT_OK && requestCode == Constants.STYEM_SUBMIT_PHOTO_GALLERY_REQUEST_CODE) {
            //提交图片

            onCutOutPhotoStyemtActivityResult(requestCode, resultCode, data);
        } else {
            super.
                    onActivityResult(requestCode, resultCode, data);
        }

    }

    /**
     * 数据更新
     */
    public void dataUpdate() {
        isUpdateData = true;
        headRightText.setVisibility(View.VISIBLE);
        myUserInfoDataAdapter.notifyDataSetChanged();
    }

    /**
     * 选择相册返回结果
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onCutOutPhotoActivityResult(int requestCode, int resultCode,
                                            Intent data) {
        if (requestCode == Constants.SELECT_IMAGE_REQUEST_CODE) {
            ArrayList<PhotoModel> selected = (ArrayList<PhotoModel>) data
                    .getSerializableExtra("photos");
            if (selected != null && selected.size() >= 1) {
                PhotoModel photoModel = selected.get(0);
                String originalPath = photoModel.getOriginalPath();
                // currUserInfJsonObject.put("avatar", "file://" +
                // originalPath);
                // headMyUserInfoView.loadData(currUserInfJsonObject,
                // avatarDisplayImageOptions);
                showOperatingProgressDialog("上传中。。。");
                myUserInfoService.uploadAvatar(originalPath);
            }
        }

    }

    /**
     * 选择相册返回结果
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onCutOutPhotoStyemtActivityResult(int requestCode, int resultCode,
                                                  Intent data) {
        File sourceFile = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                getString(R.string.currAvatarPath));
        showOperatingProgressDialog("上传中。。。");
        myUserInfoService.uploadAvatar(sourceFile.getAbsolutePath());


    }

    /**
     * 修改数据
     */
    @Click(R.id.headRightText)
    public void updateUserInfoData() {
        if (isUpdateData) {
            showOperatingProgressDialog("修改中");
            updateUserInfoService.updateUserInfo(currUserInfoJsonArray);
        }
    }

    @UiThread
    @Override
    public void updateUserInfoSuccess(JSONObject jsonObject) {
        cancelOperatingProgressDialog();
        boolean resultBoolean = TypeUtils.getJsonBoolean(
                TypeUtils.getJsonObject(jsonObject, "data"), "result");
        if (resultBoolean) {
            headRightText.setVisibility(View.GONE);
            alertMessage("修改成功");
        } else {
            alertMessage("修改失败");
        }
    }

    @UiThread
    @Override
    public void updateUserInfoError(String error) {
        cancelOperatingProgressDialog();
        alertMessage(error);
    }


    @UiThread
    @Override
    public void uploadAvatarError(String error) {
        cancelOperatingProgressDialog();
        alertMessage(error);
    }

    @UiThread
    @Override
    public void uploadAvatarSuccess(JSONObject jsonObject) {
        cancelOperatingProgressDialog();
        File sourceFile = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                getString(R.string.currAvatarPath));
        FileUtils.deleteFile(sourceFile);
        String avatar = TypeUtils.getJsonString(
                TypeUtils.getJsonObject(jsonObject, "data"), "avatar");
        currUserInfJsonObject.put("avatar", avatar);
        headMyUserInfoView.loadData(currUserInfJsonObject, bitmapLoader);
        alertMessage("修改成功");

    }

    /**
     * 显示选中性别对话框
     */
    private void showSelectSaxDialog() {
        if (saxDialog == null) {
            saxDialog = new SaxDialog(this);
        }
        saxDialog.setAllRunMethod("saxDialogAllClick");
        saxDialog.setManRunMethod("saxDialogManClick");
        saxDialog.show();

    }

    /**
     * 显示选中时间对话框
     *
     * @param title              标题
     * @param determineRunMethod 方法
     * @param defaultDate        默认时间
     */
    private void showSelectTimeDateDialog(String title, String determineRunMethod, String defaultDate) {
        if (selectTimeDateDialog == null) {
            selectTimeDateDialog = new SelectTimeDateDialog(this);
        }
        selectTimeDateDialog.show();
        selectTimeDateDialog.setDetermineRunMethod(determineRunMethod);
        SelectTimeDatePickerDialogView selectTimeDatePickerDialogView = selectTimeDateDialog.getSelectTimeDatePickerDialogView();
        selectTimeDatePickerDialogView.setDefaultDate(defaultDate);
        selectTimeDatePickerDialogView.setTitile(title);
    }

    /**
     * 退出
     */
    public void signOutClick() {
        showConfirmCancelAskDialog("是否退出当前帐号？", "signOutOperating");
    }

    /**
     * 退出操作
     */
    public void signOutOperating() {
        showOperatingProgressDialog("退出中...");
        logoutService.logout();
    }

    @UiThread
    @Override
    public void logoutSuccess(JSONObject jsonObject) {
        cancelOperatingProgressDialog();
        getBaseActivity().signOutOperating();
    }

    @UiThread
    @Override
    public void logoutError(String error) {
        cancelOperatingProgressDialog();
        alertMessage(error);
    }


    /**
     * 头像 剪切图片
     */
    public void cutOutPhoto() {
        showListSelectAlertDialog("选择", "photoGallerySelect", photoGalleryJsonArray);
    }

    /**
     * 剪切图片
     */
    public void cutOutImage() {
        File cutOutPhotoSnapFile = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                getString(R.string.cutOutPhotoSnapName));

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(Uri.fromFile(cutOutPhotoSnapFile),
                "image/JPEG");
        intent.putExtra(
                "output",
                Uri.fromFile(new File(
                        Environment
                                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                        getString(R.string.currAvatarPath))));
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", getString(R.string.outputX));
        intent.putExtra("outputY", getString(R.string.outputY));

        startActivityForResult(intent, Constants.STYEM_SUBMIT_PHOTO_GALLERY_REQUEST_CODE);
    }

    /**
     * 相册选择
     *
     * @param position 0 "拍头像",  1 "从相册选取"
     */
    public void photoGallerySelect(int position) {
        if (listSelectDialog != null && listSelectDialog.isShowing()) {
            listSelectDialog.cancel();
        }
        if (position == 0) {
            Intent intent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);

            intent.putExtra(
                    MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(new File(
                            Environment
                                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                            getString(R.string.cutOutPhotoSnapName))));
            startActivityForResult(intent, Constants.STYEM_SHEAR_PHOTO_GALLERY_REQUEST_CODE);
        } else if (position == 1) {
              /*
                             * 从相册选取
							 */
            Intent intent = new Intent(
                    "android.intent.action.PICK");
            intent.setDataAndType(
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI,
                    "image/JPEG");
            intent.putExtra(
                    "output",
                    Uri.fromFile(new File(
                            Environment
                                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                            getString(R.string.currAvatarPath))));
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);// 裁剪框比例
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX",
                    getString(R.string.outputX));// 输出图片大小
            intent.putExtra("outputY",
                    getString(R.string.outputY));
            // intent.
            startActivityForResult(intent, Constants.STYEM_SUBMIT_PHOTO_GALLERY_REQUEST_CODE);
        }
    }

    @Override
    public void onDestroyView() {
        myUserInfoDataAdapter = null;
        if (saxDialog != null && saxDialog.isShowing()) {
            saxDialog.cancel();
        }
        if (listSelectDialog != null && listSelectDialog.isShowing()) {
            listSelectDialog.cancel();
        }
        if (selectTimeDateDialog != null && selectTimeDateDialog.isShowing()) {
            selectTimeDateDialog.cancel();
        }
        if (whetherDialog != null && whetherDialog.isShowing()) {
            whetherDialog.cancel();
        }
        super.onDestroyView();
    }


}
